<?php

namespace app\web\controller;
use app\web\model\LineGoodsModel;
use app\web\model\StoreGoodsTypeModel;
use app\web\model\LineAttributesModel;
use app\common\controller\StoreBaseController;
use app\common\model\Csv;
use think\Db;
/**
 * 线下商品管理
 */
class LineGoodsController extends StoreBaseController
{
 	protected $model;
	protected $goodstypemodel;
	protected $attr_model;
	protected $csv;
	
    protected function _initialize() {
        parent::_initialize();
		$this->csv = new Csv();
		$this->model = new LineGoodsModel();
		$this->goodstypemodel = new StoreGoodsTypeModel();
		$this->attr_model = new LineAttributesModel();
    }
    /**
     * 商品管理
     * @author [lx] 
     */
    public function index( $page = 1){
    	$field = 'g.*,t.name';
    	if(request()->isPost()){
		 	$param = input('post.');
			//商品编码
			if($param['goods_no']){
				$where['g.goods_no'] = ['like', '%'.$param['goods_no'].'%'];
			}	
			//商品名称
			if($param['goods_name']){
				$where['g.goods_name'] = ['like', '%'.$param['goods_name'].'%'];
			}			
	 	}		
		$where['g.is_pk']=0;
		$where['store_id'] = session('storeInfo')['id'];
		$list=Db::name("line_goods")->alias('g')
		->join('mall_store_goodstype t','t.id=g.goods_typeid','LEFT')
		->field($field)->where($where)->order("g.add_time desc")->paginate(10);
        return $this->fetch('index', ['list' => $list]);
    }


 /**
     * 
     * 添加
     * @author [lx] 
     */
    public function add()
    {
        if(request()->isAjax()){
        	$param=input('post.');
			$param['add_time'] = now_time();
			//是否赠送	
			$param['is_zs'] = input('is_zs') ? true : false;
			if($param['is_zs']==1){
				$goodsid=$param['goodsid'];
				$goods_names=$param['goods_names'];
				$param['goodsid']=implode($goodsid, ",");
				$param['goods_names']=implode($goods_names, ",");	
				$param['store_id']	=session('storeInfo')['id'];		
			}
			if ($this->model->allowField(true)->save($param) !== false) {
                $this->success('添加成功', url('index'));
            } else {
                $this->error('添加失败');
            }
        }
		$list = $this->model->select();
		$this->assign('attr',$this->attr_model->find());
		$typelist=db('mall_goodstype')->where('pid',0)->select();
		$this->assign('trade_typelist',$typelist);
        return $this->fetch();
    }
	/**
	 * 根据1及分类获取商品二级分类
	 */
	function select_cates(){
		$list=db("mall_goodstype")->where("pid",input("cate_id"))->select();
		return json(["list"=>$list]);
	}
    public function edit($id)
    {
    	//获取商品分类
		$typelist = $this->goodstypemodel->where('agent_id',session('storeInfo')['id'])->select();
        if(request()->isAjax()){
            $param = input('post.'); 
			//是否赠送 
			$param['is_zs'] = input('is_zs') ? true : false;
			if($param['is_zs']==1){
				$goodsid=$param['goodsid'];
				$goods_names=$param['goods_names'];
				$pack=$this->model->find($id);
				if($pack['goodsid']){
					$param['goodsid']=$pack['goodsid'].",".implode($goodsid, ",");
					$param['goods_names']=$pack['goods_names'].",".implode($goods_names, ",");
				}else if($goodsid){
					$param['goodsid']=implode($goodsid, ",");
					$param['goods_names']=implode($goods_names, ",");
				}    
			}
         	if ($this->model->allowField(true)->save($param,$id) !== false) {
                $this->success('修改成功', url('goods/index'));
            } else {
                $this->error('修改失败');
            }
        }
		$store_id = session('storeInfo')['id'];
        $id = input('param.id');
		$goods = $this->model->where('id',$id)->find();
		
		$where['g.id'] = array('in',$goods['goodsid']);
		$list = Db::name("line_goods")->alias('g')
		->join('mall_store_goodstype t','t.id=g.goods_typeid','LEFT')
		->field('g.*,t.name')->where($where)->order("g.add_time desc")->paginate(10);
        
        $this->assign('goods_list',$list);
		$this->assign('typelist',$typelist);
        $this->assign('model',$goods);
		$this->assign('attr',$this->attr_model->find());
        return $this->fetch();
    }



   /**
     * [offshelf 上下架]
     * @return 
     */
    public function offshelf($id,$goods_state)
    {
    	$param = input('post.');     
		$state = 2;
		//出售中、已售罄商品下架操作    1、下架  2、上架
		if($goods_state == 2 || $goods_state == 3){
			$state = 1;
		}
     	if ($this->model->allowField(true)->save(['goods_state'=>$state],['id'=>$id]) !== false) {
            $this->success('修改成功', url('line_goods/index'));
        } else {
            $this->error('修改失败');
        }
		$field = 'g.*,t.name';
		$where['store_id'] = session('storeInfo')['id'];
		$list = Db::name("line_goods")->alias('g')
		->join('mall_store_goodstype t','t.id=g.goods_typeid','LEFT')
		->field($field)->where($where)->order("g.add_time desc")->paginate(10);
        return $this->fetch('index', ['list' => $list]);
    }

    /**
     * [del删除]
     * @author [lx] 
     */
    public function delete()
    {
        $id = input('param.id');
        if ($this->model->destroy($id)) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }
	
	//批量添加
	public function padd($p='1',$p1='1'){
		if($p == '1' || $p1=='1'){
			return $this->fetch('padd',['list'=>'1','list1'=>'1']);  
		} else{
			$p = explode(',', $p);
			$p1= explode(',', $p1);
			return $this->fetch('padd',['list'=>$p,'list1'=>$p1]);   
		}
	}	
	
	
	public function padd_ok(){
		$fileName = 'public/upload/'.$_FILES['myfile']['name'];
		$storeinfo = session('storeInfo');
		$arr_sql = $this->csv->dr($fileName);
		$f = array();
		$b = array();
		for($i=1;$i<count($arr_sql);$i++){			
			$row = $arr_sql[$i];
			$row = explode(',', $row);
			$where['goods_name'] = $row['1'];
			$where['store_id'] = $storeinfo['id'];
			$where['goods_no'] = $row['0'];
			if($this->model->where($where)->find()){
				$f[]=$row['1'];
				$b[]=$row['0'];
			}else{
				$data[$i-1]['goods_no'] = $row['0'];
				$data[$i-1]['goods_name'] = $row['1'];
				$data[$i-1]['sale_price'] = $row['2'];
				$data[$i-1]['stock'] = $row['3'];	
				$data[$i-1]['stock_flag'] = 1;		
				$data[$i-1]['add_time'] = date("Y-m-d H:i:s");
				$data[$i-1]['store_id'] = $storeinfo['id'];
				$data[$i-1]['store_name'] = $storeinfo['store_name'];
			}
		}
		$p = implode(',', $f);
		$p1 = implode(',', $b);

		$data = isset($data)?$data:"";
		if($data){
			if(Db::name('line_goods')->insertAll($data)){				
		 		$this->success('批量添加成功', url('line_goods/index'));
		 	}else{
        		$this->success('批量添加失败' , url('padd',['p'=>$p,'p1'=>$p1]));
			}
		}else{
			$this->success('批量添加失败' , url('padd',['p'=>$p,'p1'=>$p1]));
		}					
	}

	//导出csv文件
     public function dc($data){
     	if($data == '1'){
     	$agent_id=session('storeInfo')['id'];
     	$result = $this->model->where('store_id',$agent_id)->select();
     	}
		$str="商品编码,商品名称,销售价,库存,添加时间,";//设置导出第一行
        if($data == '1'){
        	$list="goods_no,goods_name,sale_price,stock,add_time";//设置导出字段
        	$filename ='商品表.csv';//设置文件名
        	$this->csv->dc($str,$list,$result,$filename);
        }else{
        	$str="商品编码,商品名称,销售价,库存,";
        	$list="";
        	$result="";
        	$filename ='csv导入样板.csv';
        	$this->csv->dc($str,$list,$result,$filename);
        }
     }
}